import Taro from '@tarojs/taro';
// 基础URL
export const BASE_URL = 'https://oa.dianchuang.club';
// export const BASE_URL = 'http://10.1.86.62:5002';

// 请求状态码
const HTTP_STATUS = {
  SUCCESS: 'OK',
  ERRARG: 'ERR.ARG',
  ERRAUTH: 'ERR.AUTH',
  ERRDATA: 'ERR.DATA',
  ERROTHER: 'ERR.OTHER',
  ERRINTERNAL: 'ERR.INTERNAL',
};

// 请求拦截器
function requestInterceptor(chain) {
  const requestParams = chain.requestParams;
  const { url } = requestParams;

  // 添加 token
  const token = Taro.getStorageSync('token');
  if (token) {
    requestParams.header = {
      ...requestParams.header,
      Authorization: `Bearer ${token}`
    };
  }

  console.log(`请求拦截: ${url}`, requestParams);
  return chain.proceed(requestParams);
}

// 响应拦截器
function responseInterceptor(chain) {
  const requestParams = chain.requestParams;

  return chain.proceed(requestParams)
    .then(res => {
      console.log(`响应: ${requestParams.url}`, res);

      const { status, data, msg } = res.data;

      if (status === HTTP_STATUS.SUCCESS) { 
        return data;
      } else if (status === HTTP_STATUS.ERRARG) {
        return Promise.reject(msg || '参数错误');
      } else if (status === HTTP_STATUS.ERRAUTH) {
        Taro.setStorageSync('token', '');
        Taro.showToast({
          title: msg || '认证错误',
          icon: 'none',
        });
        return Promise.reject(msg || '认证错误');
      } else if (status === HTTP_STATUS.ERRDATA) {
        Taro.showToast({
          title: msg || '数据错误',
          icon: 'none',
        });
        return Promise.reject(msg || '数据错误');
      } else if (status === HTTP_STATUS.ERRINTERNAL) {
        Taro.showToast({
          title: msg || '服务器错误',
          icon: 'none',
        });
        return Promise.reject(msg || '服务器错误');
      } else {
        Taro.showToast({
          title: msg || '其他错误',
          icon: 'none',
        });
        return Promise.reject(msg || '其他错误');
      }
    })
    .catch(error => {
      console.error(`请求错误: ${requestParams.url}`, error);
      // 显示错误提示
      Taro.showToast({
        title: typeof error === 'string' ? error : '网络异常',
        icon: 'none',
        duration: 2000
      });
      return Promise.reject(error);
    });
}

// 添加拦截器
Taro.addInterceptor(requestInterceptor);
Taro.addInterceptor(responseInterceptor);

// 请求函数
const request = {
  /**
   * GET请求
   * @param {string} url - 请求路径
   * @param {Object} [data={}] - 请求参数
   * @param {Object} [options={}] - 其他配置选项
   * @returns {Promise} - 返回Promise
   */
  get: (url, data = {}, options = {}) => {
    return Taro.request({
      url: `${BASE_URL}${url}`,
      data,
      method: 'GET',
      timeout: 100000,
      ...options,
      header: {
        'Content-Type': 'application/json',
        ...options.header
      }
    });
  },

  /**
   * POST请求
   * @param {string} url - 请求路径
   * @param {Object} [data={}] - 请求数据
   * @param {Object} [options={}] - 其他配置选项
   * @returns {Promise} - 返回Promise
   */
  post: (url, data = {}, options = {}) => {
    return Taro.request({
      url: `${BASE_URL}${url}`,
      data,
      method: 'POST',
      timeout: 100000,
      ...options,
      header: {
        'Content-Type': 'application/json',
        ...options.header
      }
    });
  },
};

export default request;
